package com.kakavr.emp.controller;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.google.common.collect.Maps;
import com.kakavr.auth.util.EncryptionUtils;
import com.kakavr.base.controller.BaseController;
import com.kakavr.base.exception.ValidateParamException;
import com.kakavr.emp.service.IEmployeeService;
import com.kakavr.pay.constant.WxConstant;
import com.kakavr.pay.util.HttpClientUtil;
import com.kakavr.result.MsgResult;
import com.kakavr.result.constant.MsgConstants;
import com.kakavr.shop.service.IShopAdminService;
import com.kakavr.util.SessionUtils;
/**
 * 店主扫码登录
 * @author gang.yang
 *
 */
@RestController
@RequestMapping("n/merchant")
public class MerchantController extends BaseController {
	@Resource
	private IEmployeeService employeeService;
	@Resource
	private IShopAdminService shopAdminService;

	/**
	 * 返回扫码地址（用于页面生成二维码）
	 */
	@RequestMapping(value = "getLoginCode", method = RequestMethod.GET)
	public Map<String, Object> getLoginCode(HttpServletRequest request) {
		return MsgResult.okResultData(WxConstant.getOAuthUrl(WxConstant
				.getShopRedirectUri()));
	}

	/**
	 * 接收微信返回信息
	 */
	@RequestMapping(value = "getOpenId", method = RequestMethod.GET)
	public ModelAndView getOpenId(HttpServletRequest request) {
		String state = request.getParameter("state");
		String code = request.getParameter("code");
		if (!WxConstant.LOGIN_STATE.equals(state)) {
			return new ModelAndView("redirect:/master/index.html");
		}
		if (StringUtils.isBlank(code)) {
			return new ModelAndView("redirect:/master/index.html");
		}
		String accessTokenUrl = WxConstant.getAccessTokenUrl(code);
		Map<String, Object> map = HttpClientUtil.doGet(accessTokenUrl);
		SessionUtils.getSession().setAttribute("store_session_openid",
				map.get("openid"));
		info("微信返回的openid是：" + map.get("openid"));
		Map<String, Object> user = employeeService.selectEmpInfo(map);
		if(null != user && !user.isEmpty()){
			SessionUtils.setCurUser(user);
			return new ModelAndView("redirect:/master/home.html");
		}
		return new ModelAndView("redirect:/master/bunding.html");
	}
	
	
	/**
	 * 接收微信返回openid信息
	 */
	@RequestMapping(value = "getwxOpenId", method = RequestMethod.GET)
	public Map<String, Object> getwxOpenId(HttpServletRequest request) {
		String code = request.getParameter("code");
		if (StringUtils.isBlank(code)) {
			return MsgResult.errorResult(MsgConstants.MSG_CODE_ERROR,MsgConstants.MSG_CONTENT_ERROR);
		}
		String accessTokenUrl = WxConstant.getXccOpenidUrl(code);
		Map<String, Object> map = HttpClientUtil.doGet(accessTokenUrl);
		SessionUtils.getSession().setAttribute("store_session_openid",
				map.get("openid"));
		info("微信返回的openid是：" + map.get("openid"));
		return MsgResult.okResultData(map);
	}

	/**
	 * 绑定店铺
	 */
	@RequestMapping(value = "bindingStore", method = RequestMethod.POST)
	public Map<String, Object> bindingStore(HttpServletRequest request) {
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		if (StringUtils.isBlank(userName)) {
			throw new ValidateParamException(MsgConstants.MSG_CODE_1001,
					MsgConstants.MSG_CONTENT_1001, "用户名");
		}
		if (StringUtils.isBlank(password)) {
			throw new ValidateParamException(MsgConstants.MSG_CODE_1001,
					MsgConstants.MSG_CONTENT_1001, "密码");
		}
		Object openid = SessionUtils.getSession().getAttribute(
				"store_session_openid");
		if (null == openid) {
			info("session中openid是：" + openid);
			return MsgResult.errorResult();
		}
		Map<String, Object> map = Maps.newHashMap();
		map.put("username", userName);
		Map<String, Object> user = employeeService.selectEmpInfo(map);
		int shopStatus = (int) user.get("shopStatus");
		if (shopStatus < 1) {
			throw new ValidateParamException(MsgConstants.MSG_CODE_2006,
					MsgConstants.MSG_CONTENT_2006);
		}
		int status = (int) user.get("status");
		if (status < 1) {
			throw new ValidateParamException(MsgConstants.MSG_CODE_2002,
					MsgConstants.MSG_CONTENT_2002);
		}
		Object pass = user.get("password");
		if (password.equals(pass) || EncryptionUtils.md5(password).equals(pass)) {
			int isMaster = (int) user.get("isMaster");
			if (isMaster > 0) {
				throw new ValidateParamException(MsgConstants.MSG_CODE_1002,
						"权限不足");
			}
			SessionUtils.setCurUser(user);
			if (null != user.get("openid")) {
				return MsgResult.okResult();
			}
			map.clear();
			map.put("openid", openid);
			map.put("id", user.get("shopId"));
			shopAdminService.updateShop(map);
			return MsgResult.okResult();
		}
		throw new ValidateParamException(MsgConstants.MSG_CODE_1002,
				MsgConstants.MSG_CONTENT_1002, "用户名密码");
	}

	/**
	 * 解绑
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "unbundling", method = RequestMethod.GET)
	public Map<String, Object> unbundling(HttpServletRequest request) {
		Map<String, Object> user = SessionUtils.getCurUser();
		if (null == user || null == user.get("shopId")) {
			throw new ValidateParamException(MsgConstants.MSG_CODE_2001,
					MsgConstants.MSG_CONTENT_2001);
		}
		Map<String, Object> map = Maps.newHashMap();
		map.put("openid", "");
		map.put("id", user.get("shopId"));
		shopAdminService.updateShop(map);
		return MsgResult.okResult();
	}

}
